package com.ilikesoup.instant.monitor.core;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class JdkBeanMonitor extends BeanMonitor implements InvocationHandler {

    private Object target;

    public JdkBeanMonitor(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ChangeEventTrigger changeEventTrigger;
        if (monitorMethodSupport == null || (changeEventTrigger = monitorMethodSupport.findTrigger(method)) == null) {
            return method.invoke(target, args);
        }
        Object oldVal = null;
        Invocation invocation = new Invocation(monitorContext, target, method, args);
        try {
            oldVal = changeEventTrigger.copyOldValue(invocation);
            invocation.setRetVal(method.invoke(target, args));
        } finally {
            changeEventTrigger.fireChange(invocation, oldVal, propertyChangeSupport);
        }
        return invocation.getRetVal();
    }

}
